<template>
  <div id="checkCSV">
    <div class="top">
      <!-- <h3>选择要操作的CSV:</h3> -->
      <label style='font-weight:bold'>要校验的CSV:</label>
      <input class='pathinput' type='text' placeholder='请选择要校验的CSV' disabled="disabled" :value=config.lastEditCSV />
      <button class="chooseBt" @click='chooseCSV(1)'>选择</button>
      <!-- <div class="error">对对对</div> -->
    </div>
    <div class="content" v-if="columeList.length>0">
      <div class="culumeInfo">
        <h4>勾选要校验的列:</h4>
        <div class="culumeList">
          <span v-for="(colume, index) in columeList" :key="colume.name" @click="click_colume($event, 1)" :id='index'
            :class="colume.class">
            <input name="input" type="checkbox" :value="colume.name" :checked='colume.select'>
            <label class='colume_text' style="font-size:15px;">{{colume.name}}</label>
          </span>
        </div>
      </div>

      <div class="jiaoyan">
        <h4 alt='123'>校验选项:</h4>
        <div class='jiaoyan_content'>
          <div class="simple_jiaoxian">
            <button class="jiaoxianbt" @click='uniqueCheck()' alt='判断选中的列，没个值是否唯一'>唯一性检测</button>
            <!-- <button class="jiaoxianbt" @click='numberCheck()'>数值型检测</button> -->
          </div>
          <div class="fuza_jiaoxian">

            <div class="choose_dst">
              <input class='pathinput' type='text' placeholder='选择内容所属的CSV' disabled="disabled" :value="targetCSV" />
              <button class="chooseBt" @click='chooseCSV(2)'>选择</button>
            </div>

            <div v-if='targetColumeList.length>0' class="culumeInfo">
              <h4>选中内容所属的列:</h4>
              <div class="culumeList">
                <span v-for="(colume, index) in targetColumeList" :key="colume.name" @click="click_colume($event, 2)"
                  :id='index' :class="colume.class">
                  <input name="input" type="radio" :value="colume.name" :checked='colume.select'>
                  <label class='colume_text' style="font-size:15px;">{{colume.name}}</label>
                </span>
              </div>
            </div>
            <button class="jiaoxianbt" @click='contentCheck()'>内容有效性检测</button>
          </div>
        </div>

      </div>

      <div class="result">
        <h4>输出日志：</h4>
        <div class='loglist'>
          <ul style="list-style-type: none">
            <li v-for="data in logList" :key="data.index" :class='data.class'>
              {{data.text}}
            </li>
          </ul>
        </div>

      </div>
    </div>
    <div :class=maskClass @click="clickMask()">

    </div>
  </div>
</template>

<script>
  var csv_path= "";
  function parseDom(arg) {
    var objE = document.createElement("div");

    objE.innerHTML = arg;

    return objE.childNodes;
  }
  let electron = require("electron");
  var fs = require("fs");
  var path = require("path");
  var chooseWindow;
  var config_file_path;
  import {
    BrowserWindow,
    ipcRenderer
  } from "electron";
  var csv = require("fast-csv");
  var iconvLit = require("iconv-lite");
  var self;
  export default {
    name: "checkCSV",
    components: {},
    data() {
      return {
        maskClass: "",
        config: {},
        csvData: [],
        columeList: [],
        targetCSV: "",
        targetData: [],
        targetColumeList: [],
        logList: []
      };
    },
    methods: {
      //选择要操作的csv
      chooseCSV(type) {
        if (!self.config.cpath) {
          electron.remote.dialog.showMessageBox(
            electron.remote.getCurrentWindow(), {
              title: "",
              message: "请先选择CSV所在目录"
            },
            () => {
              electron.remote.dialog.showOpenDialog(
                null, {
                  properties: ["openFile", "openDirectory", "multiSelections"]
                },
                filePaths => {
                  if (filePaths && filePaths.length > 0) {
                    self.config.cpath = filePaths;
                    self.$options.methods.saveConfig();
                    a;

                    self.$options.methods.chooseCSV();
                  }
                }
              );
            }
          );
          return;
        }

        this.maskClass = "mask";
        const winURL =
          process.env.NODE_ENV === "development" ?
          `http://localhost:9080/#chooseCSV` :
          `file://${__dirname}/index.html?#chooseCSV`;

        var parent = electron.remote.getCurrentWindow();
        chooseWindow = new electron.remote.BrowserWindow({
          width: 800,
          height: 600,
          // modal: true,
          parent: parent,
          maximizable: false,
          resizable: false,
          show: false,
          backgroundColor: "#eee",
          frame: false
        });
        chooseWindow.setResizable(false);
        chooseWindow.setMenu(null);
        chooseWindow.setMaximizable(false);
        chooseWindow.loadURL(winURL);

        chooseWindow.webContents.on("did-finish-load", function () {
          chooseWindow.show();

          var transJson = {};
          transJson.path = self.config.cpath;
          transJson.type = type;
          chooseWindow.webContents.send("dataJsonPort", transJson);
        });

        chooseWindow.on("closed", () => {
          chooseWindow = null;
        });
      },

      addLog(text, colorClass) {
        var data = {};
        data.text = text;
        data.class = colorClass;
        data.index = self.logList.length + 1;
        self.logList.push(data);
      },

      clearLog() {
        self.logList.splice(0);
      },

      //点击遮罩 关闭选择csv窗口
      clickMask() {
        if (chooseWindow) {
          chooseWindow.destroy();
          chooseWindow = null;
        }

        this.maskClass = "";
      },

      //保存程序配置
      saveConfig() {
        fs.writeFileSync(config_file_path, JSON.stringify(self.config));
      },

      initColume(type) {
        if (type == 1) self.columeList.splice(0);
        else self.targetColumeList.splice(0);

        if (type == 1) {
          if (!self.csvData.length || self.csvData.length <= 0) return;
        } else {
          if (!self.targetData.length || self.targetData.length <= 0) return;
        }
        //第0行为key 行
        var rowData;
        if (type == 1) rowData = self.csvData[0];
        else rowData = self.targetData[0];

        if (!rowData || !rowData.length) return;
        for (var i = 0; i < rowData.length; i++) {
          if (rowData[i].indexOf("[END]") < 0) {
            var data = {};
            data.name = rowData[i];
            data.select = false;
            data.class = "columeItem";
            if (type == 1) self.columeList.push(data);
            else self.targetColumeList.push(data);
          }
        }
      },

      readCSV(type, csvPath) {
        //遍历出CSV的列
        if (self.config.lastEditCSV != "") {
          //组合目标csv的路径
          var csvPath = path.join(self.config.cpath, csvPath);
          var content = fs.readFileSync(csvPath);
          // content = iconvLit.decode(content, "gbk");
          //读取csv to json
          if (type == 1) self.csvData = [];
          else self.targetData = [];

          csv
            .fromString(content)
            .on("data", function (data) {
              if (type == 1) self.csvData.push(data);
              else self.targetData.push(data);
              //初始化所有的列
            })
            .on("end", function () {
              console.log("ecnm done");
              self.$options.methods.initColume(type);
              // if (callback) callback();
            });
        }
      },

      click_colume(event, type) {
        var index = event.currentTarget.getAttribute("id");
        // event.currentTarget.innerHTML.getElementsByName('input').checked = true;
        if (type == 1) {
          self.columeList[index].select = !self.columeList[index].select;
          if (self.columeList[index].select)
            self.columeList[index].class = "columeItem_select";
          else self.columeList[index].class = "columeItem";
        } else {
          for (var i = 0; i < self.targetColumeList.length; i++) {
            self.targetColumeList[i].class = "columeItem";
            self.targetColumeList[i].select = false;
          }

          self.targetColumeList[index].class = "columeItem_select";
          self.targetColumeList[index].select = true;
        }
      },
      uniqueCheck() {
        self.$options.methods.clearLog();
        var selectColumeList = [];
        for (var i = 0; i < self.columeList.length; i++) {
          if (self.columeList[i].select) selectColumeList.push(i);
        }
        if (selectColumeList.length == 0) {
          self.$options.methods.addLog("请先选择要校验的列", "redFont");
          return;
        }
        var uniqueObj = {};
        // 从第二行开始判断;
        for (var j = 1; j < self.csvData.length; j++) {
          var key = "";
          var rowData = self.csvData[j];

          if (rowData.length > 0 && rowData[0].indexOf("#") == 0) continue;

          var uniqueKey = "";
          for (var k = 0; k < selectColumeList.length; k++) {
            uniqueKey += "@" + rowData[selectColumeList[k]];
          }

          if (uniqueObj.hasOwnProperty(uniqueKey)) {
            var err = "第" + (j + 1) + "行与" + uniqueObj[uniqueKey] + "重复";
            self.$options.methods.addLog(err, "redFont");
            return;
          } else {
            uniqueObj[uniqueKey] = "第" + (j + 1) + "行";
          }
          // console.log(uniqueObj);
        }

        self.$options.methods.addLog("校验完成，没有发现错误。", "blackFont");
      },
      numberCheck() {
        function isNumber(nubmer) {
          var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/
          return re.test(nubmer);
        }
        self.$options.methods.clearLog();
        var selectColumeList = [];
        for (var i = 0; i < self.columeList.length; i++) {
          if (self.columeList[i].select) selectColumeList.push(i);
        }
        if (selectColumeList.length == 0) {
          self.$options.methods.addLog("请先选择要校验的列", "redFont");
          return;
        }

        var uniqueObj = {};
        var keyData = self.csvData[0];
        // 从第二行开始判断;
        for (var j = 1; j < self.csvData.length; j++) {
          var key = "";
          var rowData = self.csvData[j];

          if (rowData.length > 0 && rowData[0].indexOf("#") == 0) continue;


          for (var k = 0; k < selectColumeList.length; k++) {
            var value = rowData[selectColumeList[k]];
            if (!isNumber(value)) {
              console.log(selectColumeList[k]);
              var err = '第' + (j + 1) + '行, key:' + keyData[selectColumeList[k]] + ', 值:' + value + ' 不是数字';
              self.$options.methods.addLog(err, "redFont");
              return;
            }
          }
        }

        self.$options.methods.addLog("校验完成，没有发现错误。", "blackFont");
      },
      contentCheck() {
        self.$options.methods.clearLog();
        if (self.config.lastEditCSV == '') {
          self.$options.methods.addLog('请先选择要校验CSV', 'redFont');
          return;
        }

        if (!self.targetCSV) {
          self.$options.methods.addLog('请先选择要校验的内容所在目标CSV', 'redFont');
          return;
        }

        var selectColumeList = [];
        for (var i = 0; i < self.columeList.length; i++) {
          if (self.columeList[i].select) selectColumeList.push(i);
        }
        if (selectColumeList.length == 0) {
          self.$options.methods.addLog("请先选择要校验的列", "redFont");
          return;
        }

        var targetIndex = -1;
        for (var i = 0; i < self.targetColumeList.length; i++) {
          if (self.targetColumeList[i].select) {
            targetIndex = i;
            break;
          }
        }

        if (targetIndex == -1) {
          self.$options.methods.addLog("请选择内容在目标CSV中的列", "redFont");
          return;
        }

        function isValueVaid(value, colume) {
          for (var i = 1; i < self.targetData.length; i++) {
            var rowData = self.targetData[i];
            if (rowData[colume] == value)
              return true;
          }
          return false;
        }
        var uniqueObj = {};
        var keyData = self.csvData[0];
        // 从第二行开始判断;
        for (var j = 1; j < self.csvData.length; j++) {
          var key = "";
          var rowData = self.csvData[j];

          if (rowData.length > 0 && rowData[0].indexOf("#") == 0) continue;

          for (var k = 0; k < selectColumeList.length; k++) {
            var value = rowData[selectColumeList[k]];
            if (!isValueVaid(value, targetIndex)) {
              var err = '第' + (j + 1) + '行, key:' + keyData[selectColumeList[k]] + ', 值:' + value + ' 无效';
              self.$options.methods.addLog(err, "redFont");
              return;
            }
          }
        }

        self.$options.methods.addLog('检测通过', "blackFont");

      }
    },
    beforeMount: function () {
      config_file_path = path.join(
        electron.remote.app.getPath("userData"),
        "config.txt"
      );
    },
    mounted() {
      self = this;
      fs.exists(config_file_path, function (exist) {
        if (exist) {
          var content = fs.readFileSync(config_file_path, {
            encoding: "utf-8"
          });
          self.config = JSON.parse(content);
        }

        if (!self.config.lastEditCSV) self.config.lastEditCSV = "";

        //监听选择CSV窗口返回的结果
        ipcRenderer.on("selectCSV", function (event, message) {
          var pack = JSON.parse(message);
          self.maskClass = "";
          if (pack.type == 1) {
            self.config.lastEditCSV = pack.name;
            self.$options.methods.saveConfig();
          } else self.targetCSV = pack.name;

          self.$options.methods.readCSV(pack.type, pack.name);
        });

        if (!self.config.cpath || !self.config.lastEditCSV)
          self.config.lastEditCSV = "";

        if (self.config.lastEditCSV == "") return;

        self.$options.methods.readCSV(1, self.config.lastEditCSV);
      });
    }
  };
</script>

<style scoped>
  * {
    margin: 0;
    padding: 0;
  }

  #checkCSV {
    position: absolute;
    flex-direction: column;
    height: 100%;
    width: 100%;
    background-color: eee;
    box-sizing: border-box;
    background-color: #fff;
    margin: 0px;
  }

  .result {
    margin: 10px 10px;
    /* border-top: 1px solid black; */
    text-align: left;
    /* font-weight: bold; */
    font-size: 16px;
  }

  .loglist {
    list-style-type: none;
    margin-top: 10px;
    border-top: 1px dotted black;
  }

  .top {
    /* margin-top: 30px; */
    padding-top: 25px;
    height: 10%;
    /* display: flex;
  align-items: center; */
    /* justify-content: flex-start;
  box-sizing: border-box;
  border-bottom: 1px solid darkgray;
}

.content {
  flex: 1;
  /* height: 90%; */
    /* border: 1px solid red; */
    box-sizing: border-box;
  }

  .pathinput {
    margin: 0px 10px;
    padding: 5px 5px;
    font-size: 16px;
  }

  .chooseBt {
    font-size: 16px;
    padding: 5px 5px;
    width: 6em;
    font-weight: bold;
    margin-right: 10px;
  }

  .culumeInfo {
    margin: 10px 10px;
  }

  .culumeList {
    display: flex;
    flex-wrap: wrap;
    padding: 5px 5px;
    border-top: 1px dotted black;
    /* border-bottom: 1px solid black; */
  }

  .columeItem {
    margin: 2px;
    padding: 3px;
    background-color: lightgray;
    border: 1px solid rgb(31, 95, 19);
    font-size: 16px;
    box-sizing: border-box;
  }

  .columeItem_select {
    margin: 2px;
    padding: 3px;
    background-color: rgb(13, 236, 99);
    border: 1px solid rgb(31, 95, 19);
    font-size: 16px;
    box-sizing: border-box;
  }

  .colume_text:hover,
  .columeItem:hover {
    background-color: yellow;
    cursor: pointer;
  }

  .mask {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: black;
    opacity: 0.4;
  }

  .jiaoyan {
    box-sizing: border-box;
    margin: 20px 10px 20px 10px;
  }

  .jiaoyan_content {
    border: 1px solid black;
  }

  .redFont {
    color: red;
  }

  .blackFont {
    color: black;
  }

  .jiaoxianbt {
    font-size: 25px;
    font-weight: bold;
    padding: 5px 10px;
    cursor: pointer;
    box-sizing: border-box;
    margin: 5px 10px;
  }

  .simple_jiaoxian {
    border-bottom: 1px dotted black;
  }

  .fuza_jiaoxian {
    margin-top: 30px;
    box-sizing: border-box;
  }
</style>